package com.risenb.controller;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.risenb.bean.BaseLog;
import com.risenb.bean.Manager;
import com.risenb.bean.ManagerRole;
import com.risenb.bean.Page;
import com.risenb.bean.ResultMsg;
import com.risenb.bean.Role;
import com.risenb.constant.Const;
import com.risenb.constant.DateFormat;
import com.risenb.constant.Encoding;
import com.risenb.service.BaseLogService;
import com.risenb.service.ManagerRoleService;
import com.risenb.service.ManagerService;
import com.risenb.service.ModuleService;
import com.risenb.service.RoleService;
import com.risenb.util.DateUtil;
import com.risenb.util.EncryptUtil;
import com.risenb.util.IDUtil;

@Controller
@RequestMapping("m2")
public class ManagerController extends CustomerBaseControllor {
	
	@Autowired
	ManagerService managerService;
	
	@Autowired
	ModuleService moduleService;
	
	@Autowired
	RoleService roleService;
	
	@Autowired
	BaseLogService baseLogService;
	
	@Autowired
	ManagerRoleService managerRoleService;
	
	/**
	 * 修改密码
	 */
	@RequestMapping(value = "/cp", method = RequestMethod.POST)
	public void changePassword(String oldpwd, String newpwd, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
		Manager manager = (Manager) session.getAttribute("sessionManager");
		ResultMsg resultMsg = null;
		try {
			if (!EncryptUtil.check(manager.getPassword(), oldpwd)) {
				resultMsg = new ResultMsg("300", "原密码校验失败", "", "", "", "", "修改密码失败", true);
			} else {
				manager.setPassword(EncryptUtil.encrypt(newpwd));
				managerService.modifyManagerById(manager);
				session.setAttribute("sessionManager", manager);
				resultMsg = new ResultMsg("200", "修改成功！", "", "", "", "", "密码修改成功！", true);
			}
			returnJson(resultMsg);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 跳转到修改密码页面
	 * @param mid
	 * @param request
	 * @param response
	 */
	@RequestMapping("/toCp")
	public String toCp(Integer mid, HttpServletRequest request, HttpServletResponse response){
		request.setAttribute("mid", mid);
		return "manage/changepwd2";
	}
	/**
	 * 跳转到修改密码页面
	 * @return
	 */
	@RequestMapping("/toCpPassword")
	public String toCp(){
		return "manage/changepwd";
	}
	@RequestMapping("/cp2")
	public void changePwd2(String newpwd, Integer mid, HttpServletRequest request, HttpServletResponse response) throws IOException {
		Manager manager = managerService.queryManagerById(mid);
		ResultMsg resultMsg = null;
		try {
			manager.setPassword(EncryptUtil.encrypt(newpwd));
			managerService.modifyManagerById(manager);
			resultMsg = new ResultMsg("200", "修改成功！", "", "pagination", "", "closeCurrent", "密码修改成功！", true);
		} catch (Exception e) {
			resultMsg = new ResultMsg("300", "修改失败", "", "", "", "closeCurrent", "", true);
		}
		returnJson(resultMsg);
	}

	// 批量获取管理员
	@RequestMapping(value = "/g1")
	public ModelAndView selectmanage(Map<String, Object> params, Integer pageSize, Integer pageCurrent, HttpServletRequest request,
			HttpServletResponse response) {
		String username = request.getParameter("username");
		Page<Manager> page = new Page<Manager>().setPageNo(pageCurrent == null ? 1 : pageCurrent).setPageSize(pageSize == null ? 15 : pageSize)
				.setParams(params);
		page.getParams().put("username", username);
		List<Manager> managers = managerService.queryByPage(page);
		page.setResults(managers);
		ModelAndView mv = new ModelAndView("manage/manager");
		mv.addObject("roles", roleService.queryAll(new Role().setStatus(0)));
		mv.addObject("page", page);
		return mv;
	}

	// 获取单个管理员
	@RequestMapping(value = "g2")
	public ModelAndView getManagerById(Integer mid, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mv = new ModelAndView("manage/editmanager");
		if (mid != null) {
			Manager m = managerService.queryManagerById(mid);
			mv.addObject("manager", m);
		}
		return mv;
	}

	// 编辑管理员
	@RequestMapping(value = "e1")
	public void editManager(@RequestBody @ModelAttribute Manager manager, HttpSession session, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		int row = 0;
		Manager mng = (Manager) session.getAttribute("sessionManager");
		manager.setOperatime(new Date());
		manager.setOperator(mng.getId());
		ResultMsg resultMsg = null;
		if (manager.getId() == null) {
			manager.setCreatetime(new Date());
			manager.setPassword(EncryptUtil.encrypt(manager.getPassword()));
			manager.setIdkey(IDUtil.manegerID());
			BaseLog bs = new BaseLog(mng.getIdkey(), new Date(), "操作员管理", manager.getIdkey(), "添加操作员信息", 0, 0);
			if (managerService.queryManager(new Manager().setUsername(manager.getUsername())) != null) {
				bs.setStatus(1);
				baseLogService.createBaseLog(bs);
				resultMsg = new ResultMsg("300", "操作失败", "", "", "", "", "操作失败");
				returnJson(resultMsg);
				return;
			}
			row = managerService.createManager(manager);
			baseLogService.createBaseLog(bs);
		} else {
			if (manager.getPassword().length() != 32) {
				manager.setPassword(EncryptUtil.encrypt(manager.getPassword()));
			}
			BaseLog bs = new BaseLog(mng.getIdkey(), new Date(), "操作员管理", manager.getIdkey(), "修改操作员信息", 0, 0);
			row = managerService.modifyManagerById(manager);
			baseLogService.createBaseLog(bs);
		}
		if (row > 0) {
			resultMsg = new ResultMsg("200", "操作完成", "", "manager", "", "", "操作完成", true);
		} else {
			resultMsg = new ResultMsg("300", "操作失败", "", "manager", "", "", "操作失败", true);
		}
		returnJson(resultMsg);
	}

	// 批量删除
	@RequestMapping(value = "d1")
	public void deleteManager(String ids, HttpSession session, HttpServletRequest request, HttpServletResponse response) throws IOException {
		List<String> list = Arrays.asList(ids.split(","));
		int row = managerService.removeManagerByIds(list);
		ResultMsg resultMsg = null;
		if (row > 0) {
			resultMsg = new ResultMsg("200", "操作完成", "", "manager", "", "", "操作完成");
		} else {
			resultMsg = new ResultMsg("300", "操作失败", "", "manager", "", "", "操作失败");
		}
		returnJson(resultMsg);
	}

	// 冻结
	@RequestMapping(value = "d2")
	public void freezeManage(Integer mid, HttpSession session, HttpServletRequest request, HttpServletResponse response) throws IOException {
		Manager mng = (Manager) session.getAttribute(Const.SESSION_MANAGER);
		Manager manager = managerService.queryManagerById(mid);
		BaseLog baseLog = null;
		if (manager.getStatus() == null || manager.getStatus().equals("1")) {
			manager.setStatus("0");
			baseLog = new BaseLog(mng.getIdkey(), new Date(), "操作员管理", manager.getIdkey(), "启用用户", 0, 0);
		} else {
			manager.setStatus("1");
			baseLog = new BaseLog(mng.getIdkey(), new Date(), "操作员管理", manager.getIdkey(), "冻结用户", 0, 0);
		}
		int row = managerService.modifyManagerById(manager);
		
		ResultMsg resultMsg = null;
		if (row > 0) {
			baseLogService.createBaseLog(baseLog.setStatus(0));
			resultMsg = new ResultMsg("200", "操作完成", "", "manager", "", "", "");
		} else {
			baseLogService.createBaseLog(baseLog.setStatus(1));
			resultMsg = new ResultMsg("300", "操作失败", "", "manager", "", "", "操作失败");
		}
		returnJson(resultMsg);
	}

	@RequestMapping(value = "sr")
	public void setRoleOfManager(Integer mid, String rids, HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {
		ResultMsg resultMsg = null;
		try {
			Manager manager = (Manager) session.getAttribute("sessionManager");
			managerRoleService.removeManagerRoleByManagerId(mid);
			if (rids != null) {
				String[] ids = rids.split(",");
				for (int i = 0; i < ids.length; i++) {
					if (!StringUtils.isBlank(ids[i])) {
						ManagerRole mr = new ManagerRole();
						mr.setOperatime(new Date());
						mr.setOperator(manager.getId());
						mr.setRoleid(Integer.parseInt(ids[i]));
						mr.setManageid(mid);
						managerRoleService.createManagerRole(mr);
					}
				}
			}
			resultMsg = new ResultMsg("200", "操作完成", "", "manager", "", "", "");
		} catch (Exception e) {
			resultMsg = new ResultMsg("300", "操作失败", "", "manager", "", "", "操作失败");
		}
		returnJson(resultMsg);
	}

	@RequestMapping("/ep")
	public void exportSystemLog(String expids, HttpServletResponse response) {
		response.setContentType("application/binary;charset=ISO8859_1");
		try {
			ServletOutputStream outputStream = response.getOutputStream();
			String fileName = new String(("操作人员信息记录" + DateUtil.getCurrDateStr(DateFormat.YYYYMMDD)).getBytes(), Encoding.ISO_8859_1);
			response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xlsx");// 组装附件名称和格式
			List<Manager> sl = null;
			if (StringUtils.isBlank(expids)) {
				sl = managerService.queryAll();
			} else {
				sl = managerService.queryAll(Arrays.asList(expids.split(",")));
			}
			String[] titles = { "操作员编号", "用户名", "姓名", "联系电话", "创建时间", "修改时间", "状态" };
			managerService.exportExcel(sl, titles, outputStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
